<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;

/**
 * 提现
 */
class Withdraw extends Api
{
    protected $noNeedLogin = ['*'];

	public function _initialize(){
		
	}

    public function index(){
        $info = ['orderno'=>'sjzz'.date('Ymd').mt_rand(1000, 9999),'amount'=>0.5,'openid'=>'o_sKy5N0XBUBqa5hrSHRxqfIq5J4'];
        $this->sendredpack($info);
    }


    /**
     * 商家转账到零钱
     *
     * @ApiMethod (POST)
     * @param string $intransfer_detail_listfo 转账明细列表
     * $intransfer_detail_listfo = [[
     *     'out_detail_no'=> $out_detail_no, //批次单号
     *     'transfer_amount'=>$transfer_amount, //转账金额
     *    'transfer_remark'=>$transfer_remark, //转账名称
     *     'openid'=>$openid, //用户openid
     * ]];
     * @param string $batch_name    转账说明
     * @param string $total_amount    转账总金额 单位为"分"  总金额为明细列表总金额
     */
    public function sendredpack($intransfer_detail_listfo = [],$batch_name = '活动奖励',$total_amount,$appid = 'wx84f56a63b9f63e03')
    {
       
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        $pars = [];
        $pars['appid'] = 'wx84f56a63b9f63e03';//直连商户的appid
        $pars['out_batch_no'] = 'sjzz'.date('Ymd').mt_rand(1000, 9999);//商户系统内部的商家批次单号，要求此参数只能由数字、大小写字母组成，在商户系统内部唯一
        $pars['batch_name']   = $batch_name;//该笔批量转账的名称
        $pars['batch_remark'] = $batch_name;//转账说明，UTF8编码，最多允许32个字符
        $pars['total_amount'] = $total_amount;//转账总金额 单位为“分”
        $pars['total_num']    = 1;//转账总笔数
        $pars['transfer_detail_list']  = $intransfer_detail_listfo;//转账明细列表
        $token  = $this->getTokenSuLa($pars);//获取token
        $res    = $this->https_request($url,json_encode($pars),$token);//发送请求//json_encode($pars,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)
        $resArr = json_decode($res,true);
        if($resArr && !empty($resArr['batch_status']) && $resArr['batch_status'] =='ACCEPTED'){
            return $resArr;
        }else{
            return $resArr;
        }
    }

    public function getTokenSuLa($pars)
    { 
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        $http_method = 'POST';//请求方法（GET,POST,PUT）
        $timestamp   = time();//请求时间戳
        $url_parts   = parse_url($url);//获取请求的绝对URL
        $nonce       = $timestamp.rand('10000','99999');//请求随机串
        $body        = json_encode((object)$pars);//请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];
        
        $pathcert =  ROOT_PATH . "public/uploads/sula_zs/apiclient_cert.pem";//商户里下载证书工具按步骤操作获取
        $pathkey = ROOT_PATH . "public/uploads/sula_zs/apiclient_key.pem";//商户里下载证书工具按步骤操作获取
        
        $apiclient_cert_path = $pathcert;//'https://'.substr($pathcert,13);
        $apiclient_key_path  = $pathkey;//'https://'.substr($pathkey,13);
        
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path,false, stream_context_create($stream_opts)));
        $serial_no          = '592CC7CDD2E2B273CA440C661A2BFA8643C0117F';//证书序列号
        $mch_private_key    = file_get_contents($apiclient_key_path,false, stream_context_create($stream_opts));//密钥
        $merchant_id = '1666321588';//商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message = $http_method."\n".
        $canonical_url."\n".
        $timestamp."\n".
        $nonce."\n".
        $body."\n";
        // var_dump($message);exit;
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        $sign = base64_encode($raw_sign);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        // var_dump($token);exit;
        return $token;
    }


    public function getToken($pars)
    { 
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        $http_method = 'POST';//请求方法（GET,POST,PUT）
        $timestamp   = time();//请求时间戳
        $url_parts   = parse_url($url);//获取请求的绝对URL
        $nonce       = $timestamp.rand('10000','99999');//请求随机串
        $body        = json_encode((object)$pars);//请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];
        
        $pathcert =  ROOT_PATH . "public/uploads/zs/apiclient_cert.pem";//商户里下载证书工具按步骤操作获取
        $pathkey = ROOT_PATH . "public/uploads/zs/apiclient_key.pem";//商户里下载证书工具按步骤操作获取
        
        $apiclient_cert_path = $pathcert;//'https://'.substr($pathcert,13);
        $apiclient_key_path  = $pathkey;//'https://'.substr($pathkey,13);
        
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path,false, stream_context_create($stream_opts)));
        $serial_no          = '710B251FBFC28C444B89585B94B3485D1350B1EC';//证书序列号
        $mch_private_key    = file_get_contents($apiclient_key_path,false, stream_context_create($stream_opts));//密钥
        $merchant_id = '1650562174';//商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message = $http_method."\n".
        $canonical_url."\n".
        $timestamp."\n".
        $nonce."\n".
        $body."\n";
        // var_dump($message);exit;
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        $sign = base64_encode($raw_sign);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        // var_dump($token);exit;
        return $token;
    }
    

    function https_request($url,$data = null,$token){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [
            'Authorization:WECHATPAY2-SHA256-RSA2048 '.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if(!empty($headers)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}